import { View } from '@tarojs/components'
import { OnGetUserInfoEventDetail } from '@tarojs/components/types/Button'
import { BaseEventOrig } from '@tarojs/components/types/common'
import Taro, { Config, useDidShow, UserInfo, useState } from '@tarojs/taro'
import { BaiduMapResponse } from 'src/types/response'
import { AtButton } from 'taro-ui'
import { Header } from './components/Header/Header'
import { HealthReport } from './components/HealthReport/HealthReport'
import './index.less'
import { Card } from '../../components/Card/Card'

export function Index() {
  const [isAuth, setAuthState] = useState(true)
  const [userInfo, setUserInfo] = useState<UserInfo>({} as UserInfo)
  const [city, setCity] = useState('')

  useDidShow(async () => {
    const setting = await Taro.getSetting()

    if (!setting.authSetting['scope.userInfo']) {
      setAuthState(false)
      return
    }

    await getUserInfo()
  })

  const getUserInfo = async () => {
    const { userInfo } = await Taro.getUserInfo()
    setUserInfo(userInfo)
    setAuthState(true)
    await getCity()
  }

  const onGetUserInfo = async (result: BaseEventOrig<OnGetUserInfoEventDetail>) => {
    if (result.detail.userInfo) {
      Taro.showToast({ title: '授权登录成功~' })
      await getUserInfo()
      return
    }

    Taro.showModal({
      title: '温馨提示',
      content: '请授权登录哦~',
      showCancel: false,
    })
  }

  const getCity = async () => {
    try {
      await Taro.authorize({
        scope: 'scope.userLocation',
      })

      const { latitude, longitude } = await Taro.getLocation({})

      const { data } = await Taro.request<BaiduMapResponse>({
        url: `https://api.map.baidu.com/geocoder/v2/?ak=lr7Cl7QkbGqH5irqlK5wZvwQ9duK84hc&location=${latitude},${longitude}&output=json`,
      })

      setCity(data.result.addressComponent.city)
    } catch (e) { }
  }

  if (!isAuth) {
    return (
      <View className="auth-container">
        <AtButton className="" openType="getUserInfo" lang="zh_CN" onGetUserInfo={onGetUserInfo} type="primary">
          微信用户快速登录
        </AtButton>
      </View>
    )
  }

  const toKnowledge = () => {
    Taro.navigateTo({
      url: '/pages/knowledge/index',
    })
  }

  const toFillReport = () => {
    Taro.navigateToMiniProgram({
      appId: 'wx34b0738d0eef5f78',
      path: 'pages/forms/publish?token=nuv0es',
    })
  }

  return (
    <View className="container">
      <Header city={city} name={userInfo.nickName} avatar={userInfo.avatarUrl} />
      <View className="content">
        <HealthReport />
        <View className="card-container">
          <Card onClick={toFillReport} title={'南昌大学返校登记'} desc={'输入返校日期车次，查询病患同行情况'} />
          <Card onClick={toKnowledge} title={'校园防疫工具合集'} desc={'防疫小妙招、网课、肺炎咨询等'} />
        </View>
      </View>
    </View>
  )
}

Index.config = {
  navigationBarTitleText: '首页',
} as Config
